package com.ray.woodencreate.aspect;

import com.alibaba.fastjson.JSON;
import com.ray.woodencreate.beans.CommonValue;
import com.ray.woodencreate.logs.SystemLogBuilder;
import com.ray.woodencreate.util.MsgIdUtil;
import com.ray.woodencreate.util.RequestMsgUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author bo shen
 * @Description: 请求拦截
 * @Class: PerformanceAspect
 * @Package com.toptoday.woodencreate.aspect
 * @date 2018/10/10 18:02
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Aspect
@Component
@Slf4j
@Order(1001)
public class RequestAspect {

    /**
     * 统一拦截所有 Mapping请求
     */
    @Pointcut("@annotation(org.springframework.web.bind.annotation.Mapping)" +
            "|| @annotation(org.springframework.web.bind.annotation.RequestMapping)" +
            "|| @annotation(org.springframework.web.bind.annotation.DeleteMapping)" +
            "|| @annotation(org.springframework.web.bind.annotation.PutMapping)" +
            "|| @annotation(org.springframework.web.bind.annotation.PostMapping)" +
            "|| @annotation(org.springframework.web.bind.annotation.GetMapping)")
    public void controllerLog() {
    }

    /**
     * 统一拦截所有 Mapping请求
     */
    @Pointcut("@annotation(com.ray.woodencreate.annotation.NoLog)")
    public void NoLog() {
    }


    /**
     * @param joinPoint
     * @throws Throwable
     */
    @Before("controllerLog() && !NoLog()")
    public void start(JoinPoint joinPoint) throws Throwable {
        //生成消息号
        MsgIdUtil.createMsgId();
        //获取方法名 参数
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            //创建网络消息信息
            RequestMsgUtil.createMsg(request, CommonValue.APP_NAME);
            String body = String.format("请求路径[%s]-[%s],参数:%s",joinPoint.getSignature().getDeclaringTypeName(),joinPoint.getSignature().getName()
                    , JSON.toJSON(request.getParameterMap()));
            log.info(new SystemLogBuilder().appendLevelRequest().appendMsg(body).bulidString());
        }
    }



}
